package io.nio;

import framework.AbstractTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileAppend extends AbstractTest {

  @Override
  public void test(String[] args) {
    super.test(args);

    String inPath = getDefInputFile(args);
    String outPath = getDefOutputFile(args);

    appendToFile(new File(outPath), new File(inPath));


  }


  public static void appendToFile(File dest, File src) {

    FileOutputStream writer = null;
    try {
      // true表示以追加形式写文件
      writer = new FileOutputStream(dest, true);
      InputStream source = new FileInputStream(src);

      long nread = 0L;
      byte[] buf = new byte[BUFFER_SIZE];
      int n;
      while ((n = source.read(buf)) > 0) {
        writer.write(buf, 0, n);
        nread += n;
      }
    } catch (IOException e) {
      // Log.printErrorStackTrace(TAG, "appendToFile", e);
    } finally {
      // close(writer);
    }
  }

  private static final int BUFFER_SIZE = 8192;

  private static long copy(InputStream source, OutputStream sink) throws IOException {
    long nread = 0L;
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while ((n = source.read(buf)) > 0) {
      sink.write(buf, 0, n);
      nread += n;
    }
    return nread;
  }

}
